package com.gin.no_gay_alliance.fragment.topic;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.enums.SubForumType;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.adpter.SearchAreaAdapter;
import com.gin.no_gay_alliance.adpter.SearchHistoryAdapter;
import com.gin.no_gay_alliance.customview.PagerButton;
import com.gin.no_gay_alliance.databinding.FragmentTopicSearchBinding;
import com.gin.no_gay_alliance.manager.history.SearchHistoryManager;
import com.gin.no_gay_alliance.param.SearchArea;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.EditTextUtils;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.ParcelableUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 版面和合集搜索
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/5 14:43
 **/
public class TopicSearchFragment extends BaseTopicListFragment<FragmentTopicSearchBinding> implements TextView.OnEditorActionListener, SearchHistoryAdapter.OnKeywordSelectedListener {
    /**
     * 搜索区域
     */
    private List<SearchArea> searchAreas;
    private SearchAreaAdapter adapter;
    private SearchHistoryAdapter searchHistoryAdapter;

    /**
     * 提供布局文件中的Toolbar
     *
     * @return toolbar
     */
    @Nullable
    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }


    /**
     * 创建选项菜单
     *
     * @param menu     菜单
     * @param inflater 渲染器
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        // 装载搜索菜单按钮
        inflater.inflate(R.menu.search_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 点击搜索按钮时执行搜索
        if (item.getItemId() == R.id.menu_item_search) {
            sendSearch();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 关键字输入框自动聚焦
        EditTextUtils.focusSelect(requireContext(), b.et, handler);
    }

    @Override
    public void onPause() {
        super.onPause();
        // 关闭输入法
        InputMethodManagerUtils.hide(b.et);
    }

    /**
     * 提供布局文件中的翻页按钮
     *
     * @return {@link PagerButton}
     */
    @NonNull
    @Override
    protected PagerButton initPagerButton() {
        return b.btnPager;
    }

    /**
     * 提供布局文件中的刷新按钮
     *
     * @return {@link ImageButton}
     */
    @NonNull
    @Override
    protected ImageButton initRefreshButton() {
        return b.btnRefresh;
    }

    /**
     * 提供布局文件中的 主题列表分页ViewPager2
     *
     * @return ViewPager2
     */
    @NonNull
    @Override
    protected ViewPager2 initViewPager2() {
        return b.vp2;
    }

    @Override
    protected void onCreateView() {
        super.onCreateView();
        // 绑定软键盘搜索键
        b.et.setOnEditorActionListener(this);

        searchAreas = ParcelableUtils.copy(param.searchAreas);
        if (searchAreas.size() == 1) {
            // 仅有一个区域
            SearchArea searchArea = searchAreas.get(0);
            b.tv.setVisibility(View.VISIBLE);
            b.tv.setText(String.format(Locale.CHINA, "在%s %s(%d) 中搜索", searchArea.type, searchArea.name, searchArea.id));
        } else {
            // 多个区域 : 装填搜索区域
            b.recyclerView.setVisibility(View.VISIBLE);
            adapter = new SearchAreaAdapter(searchAreas);
            b.recyclerView.setAdapter(adapter);
        }

        // 装载搜索历史
        searchHistoryAdapter = new SearchHistoryAdapter(requireContext(), SearchHistoryManager.DATA_STORE_KEY_SEARCH_TOPIC_HISTORY, this);
        b.rvSearchHistory.setAdapter(searchHistoryAdapter);
        b.tvClearHistory.setOnClickListener(this);


        showHistory(true);
        showResult(false);
        b.et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当清空输入框时，显示搜索历史
                if (ObjectUtils.isEmpty(s)) {
                    showHistory(true);
                    showResult(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 点击事件统一处理
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        // 清空搜索历史
        if (v == b.tvClearHistory) {
            searchHistoryAdapter.clear();
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // 当按下软键盘搜索键时，执行搜索
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 执行搜索
            sendSearch();
            return true;
        }
        return false;
    }

    /**
     * 选中关键字时的回调
     *
     * @param keyword 被选中的关键字
     */
    @Override
    public void onKeywordSelected(String keyword) {
        b.et.setText(keyword);
        sendSearch();
    }

    /**
     * 执行搜索
     */
    private void sendSearch() {
        //隐藏搜索历史，显示搜索结果
        showHistory(false);
        showResult(true);

        //关闭软键盘
        InputMethodManagerUtils.hide(b.et);
        // 取消焦点
        b.et.clearFocus();

        Log.d(this.getClass().getSimpleName(), "执行搜索");

        // 搜索参数公共部分
        TopicListParam p = new TopicListParam();
        p.keyword = b.et.getText().toString();
        p.searchContent = b.swSearchContent.isChecked();
        p.recommendOnly = b.swRecommendOnly.isChecked();

        if (param.type == TopicListParam.Type.COL_SEARCH) {
            // 合集搜索
            p.type = param.type;
            p.colTid = param.colTid;
        }
        // 选中的搜索区域
        List<SearchArea> checkedAreas = searchAreas.stream().filter(i -> i.checked).collect(Collectors.toList());
        if (checkedAreas.isEmpty()) {
            toast("必须至少选中一个搜索区域");
            return;
        } else if (checkedAreas.size() == 1) {
            // 只选中了一个区域
            SearchArea searchArea = checkedAreas.get(0);
            if (searchArea.type.equals(SubForumType.COL.name)) {
                // 合集搜索
                p.type = param.type;
                p.colTid = searchArea.id;
            } else {
                // 单版面搜索
                p.type = TopicListParam.Type.FORUM_SEARCH;
                p.forumId = String.valueOf(searchArea.id);
            }
        } else {
            // 多区域搜索
            p.type = TopicListParam.Type.FORUM_SEARCH;
            p.forumId = checkedAreas.stream().map(i -> String.valueOf(i.id)).collect(Collectors.joining(","));
        }

        // 记录搜索历史
        searchHistoryAdapter.add(p.keyword);

        // 装载主题页，执行搜索
        initAdapter(p);

    }

    /**
     * 搜索历史相关控件显示
     */
    private void showHistory(boolean show) {
        ViewUtils.setGone(!show, b.rvSearchHistory, b.tvClearHistory, b.tvSearchHistory);
    }

    /**
     * 搜索结果相关控件显示
     */
    private void showResult(boolean show) {
        ViewUtils.setGone(!show, b.vp2, b.btnPager, b.btnRefresh);
    }
}
